<template>
    <div>
        <span @click="handleVisible(true)">
            <!-- 自定义选择按钮 -->
            <slot name="btn" :selectedRow="selectedRow" :chooseIds="chooseIds">
                <el-button :disabled="disabled"> {{ title }} </el-button>
            </slot>
        </span>
        <el-dialog
            class="draw_template_dialog"
            :title="title"
            v-model="visible"
            width="80%"
            @close="closeCallback()"
            append-to-body>
            <div class="draw_template_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                    <el-row justify="space-between" :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="活动名称" prop="activityName">
                                <el-input v-model="form.activityName" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="来源店铺" prop="shopId">
                                <el-select v-model="form.shopId" filterable placeholder="全部">
                                    <el-option
                                        v-for="item in shopList"
                                        :key="item.shopId"
                                        :label="item.shopName"
                                        :value="item.shopId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="text-align: right">
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-table
                v-loading="loading"
                :data="tableList"
                @selection-change="handleSelectionChange"
                style="margin-top: 20px"
                height="350"
                class="choose-custom-table"
                ref="multipleTableRef">
                <el-table-column v-if="isMulti" type="selection" width="55" />
                <el-table-column v-for="{ prop, ...rest } in tableColumnsCopy" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <el-button
                            v-if="prop === 'operation'"
                            size="small"
                            @click="handleSelect(row)"
                            :disabled="selectedRow?.id === row.id">
                            {{ selectedRow?.id === row.id ? '已选择' : '选择' }}</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="custom-page">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
            <template #footer v-if="isMulti">
                <div style="flex: auto" class="custom-footer">
                    <div class="selected-total">
                        已选中<span>{{ chooseIds.length }}</span
                        >个
                    </div>
                    <div>
                        <el-button plain @click="handleVisible(false)">取消</el-button>
                        <el-button type="primary" @click="handleConfirm">确认</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="ZwChooserDraw">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { cloneDeep, isEmpty } from '@/commons/utils';
import { getShopListHook } from '@/hooks';
import { ElMessage } from 'element-plus';
import request from '@/request';
import Pagination from '@/components/Pagination.vue';
// import { ZwRequest } from '@zhongwan/js-sdk';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    // 单选/多选，默认单选
    isMulti: {
        type: Boolean,
        default: false
    },
    // 是否禁用
    disabled: {
        type: Boolean,
        default: false
    },
    // 单选选择后是否关闭窗口
    selectClose: {
        type: Boolean,
        default: true
    },
    // value如果是单选的话结构至少包含id,{id: '抽奖活动ID'}，如果是多选为抽奖活动集合['抽奖活动id1']
    value: {
        type: [Object, Array],
        default: () => null
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 查询表格 start ---------------------------------- */
const form = reactive({
    page: 1,
    perPage: 10,
    shopId: 0,
    activityName: '', // 活动名
    choiceSpike: 1,
    choiceAllShop: 1
});
const formClone = cloneDeep(form); // 查询表单备份
const formRef = ref();
let shopList = reactive([]); // 店铺下拉列表
let loading = ref(false);

const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '活动名称', prop: 'activityName', showOverflowTooltip: true, minWidth: '100' },
    { label: '活动时间', prop: 'activityTime', width: '400' },
    { label: '来源店铺', prop: 'shopName', showOverflowTooltip: true, minWidth: '100' },
    { label: '状态', prop: 'realStatusName' }
]);
const tableColumnsCopy = computed(() => {
    const cols = cloneDeep(tableColumns);
    if (!props.isMulti) {
        cols.push({ label: '操作', prop: 'operation', width: '100' });
    }
    return cols;
});
/* ---------------------------------- 查询表格 end ---------------------------------- */

let selectedRow = reactive({}); // 已选中的抽奖活动
const multipleTableRef = ref();
let chooseIds = reactive([]); // 多选的抽奖活动ids
let chooseIdsClone = reactive([]); // 多选的抽奖活动ids
watch(
    () => props.value,
    val => {
        if (props.isMulti) {
            chooseIds.length = 0;
            chooseIdsClone.length = 0;
            Object.assign(chooseIds, val || []);
            Object.assign(chooseIdsClone, val || []);
            return;
        }
        if (isEmpty(val)) {
            const keys = Object.keys(selectedRow);
            let obj = {};
            keys.forEach(item => {
                obj[item] = null;
            });
            Object.assign(selectedRow, obj);
            return;
        }
        Object.assign(selectedRow, val || {});
    },
    {
        immediate: true,
        deep: true
    }
);

const toggleRowSelection = rows => {
    rows.forEach(item => {
        multipleTableRef?.value?.toggleRowSelection(item);
    });
};

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let visible = ref(false);
let isClose = ref(true);
// 展示隐藏
const handleVisible = (isVisible = false) => {
    if (props.disabled) {
        return;
    }
    visible.value = isVisible;
    if (visible.value) {
        isClose.value = true;
        getShopList();
        searchHandler();
    }
};
const closeCallback = visible => {
    // 关闭后重置表格
    // multipleTableRef.value?.clearSelection();
    formRef.value.resetFields();
    Object.assign(form, cloneDeep(formClone));
    if (isClose.value) {
        chooseIds.length = 0;
        Object.assign(chooseIds, cloneDeep(chooseIdsClone));
    }
    isClose.value = false;
    // searchHandler();
};
const title = computed(() => {
    return `${props.value?.id || props.value?.length ? (props.isMulti ? '继续' : '重新') : ''}选择${
        props.value?.id || props.value?.length ? '' : '抽奖活动'
    }`;
});
/* ---------------------------------- 控制弹窗 end ---------------------------------- */

const handleSelect = row => {
    if (props.selectClose) {
        // const keys = Object.keys(selectedRow);
        // let obj = {};
        // keys.forEach(item => {
        //     obj[item] = null;
        // });
        // Object.assign(selectedRow, row);
        handleVisible(false);
    } else {
        // Object.assign(selectedRow, row);
    }
    Object.assign(selectedRow, row);
    emit('handle-confirm', row);
};

const handleSelectionChange = val => {
    // chooseIds
    if (!visible.value) {
        return;
    }
    nextTick(() => {
        const selectList = val.map(item => item.id);
        const notSelectedList = tableList.reduce((prev, { id }) => {
            if (!selectList.includes(id)) {
                prev.push(id);
            }
            return prev;
        }, []);
        const ids = chooseIds.filter(item => !notSelectedList.includes(item));
        chooseIds.length = 0;
        Object.assign(chooseIds, [...new Set([...ids, ...selectList])]);
    });
};

// 确认按钮
const handleConfirm = async () => {
    if (chooseIds.length < 1) {
        ElMessage({
            type: 'error',
            message: '请先选择抽奖活动'
        });
        return;
    }
    isClose.value = false;
    emit('handle-confirm', chooseIds);
    handleVisible(false);
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    Object.assign(form, formClone);
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    loading.value = true;
    const res = await request('getActivityDrawList', { ...form, shopId: form.shopId || null });
    const list = (res?.data?.list || []).map(item => {
        item.activityTime = `${item.activityStartTime}至${item.activityEndTime}`;
        item.realStatusName = item.activityStatusName.realStatusName;
        item.realStatus = item.activityStatusName.realStatus;
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
    nextTick(() => {
        if (props.isMulti) {
            multipleTableRef.value?.clearSelection();
            toggleRowSelection(tableList.filter(item => chooseIds.includes(item.id)));
        }
        loading.value = false;
    });
};

// 获取店铺
const getShopList = async () => {
    const { data } = await getShopListHook();
    shopList.length = 0;
    const list = data?.list || [];
    list.unshift({ shopName: '全部', shopId: 0 });
    Object.assign(shopList, list);
};
</script>

<style lang="scss">
.draw_template_dialog {
    max-width: 1000px;
    min-width: 900px;
    /* min-height: 570px; */
    .choose-custom-table {
        border-bottom: 1px solid #eaeaea !important;
    }
}
</style>
<style lang="scss" scoped>
.draw_template_dialog {
    &_header {
        width: 100%;
        .el-form > div {
            flex-wrap: nowrap;
        }
    }
    .center-operation {
        padding: 20px 0;
        display: flex;
        border-bottom: 1px solid #eaeaea;
        justify-content: space-between;
    }
    .custom-page {
        height: auto;
        overflow: hidden;
    }
    .custom-footer {
        flex: 1 1 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
    }
    .selected-total {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        span {
            margin: 0 4px;
            color: #ff6b00;
        }
    }
}
</style>
